package com.example.dialog.Tools;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

import android.os.AsyncTask;

public class SendEmail {

    public static void sendMail(final String to, final String subject, final String body) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                final String username = "2399534910@qq.com";  // 你的QQ邮箱
                final String password = "mtgbmgmdnbnbdjej";  // 你的授权码

                // 设置邮件服务器
                Properties properties = new Properties();
                properties.put("mail.smtp.host", "smtp.qq.com");  // QQ邮箱 SMTP 服务器
                properties.put("mail.smtp.port", "465");  // 端口号
                properties.put("mail.smtp.auth", "true");  // 需要身份验证
                properties.put("mail.smtp.ssl.enable", "true");  // 启用SSL
                properties.put("mail.smtp.socketFactory.port", "465"); // SSL端口

                // 创建会话
                Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);  // 你的邮箱和授权码
                    }
                });

                try {
                    // 创建邮件内容
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(username));  // 发件人
                    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));  // 收件人
                    message.setSubject(subject);  // 邮件主题
                    message.setText(body);  // 邮件内容

                    // 发送邮件
                    Transport.send(message);

                    System.out.println("邮件已发送成功");

                } catch (MessagingException e) {
                    e.printStackTrace();
                }

                return null;
            }
        }.execute();
    }
}


